package com.woke.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.http.HttpMethods;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.woke.adapter.OnItemClickListener;
import com.woke.adapter.PromoteCodeViewProvider;
import com.woke.addressactivity.UserpromoteIIActivity;
import com.woke.data.UserPromoteCode;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

import static me.drakeet.multitype.MultiTypeAsserts.assertAllRegistered;

/**
 * 推广码(分为1贷款、2信用卡) 列表
 */
public class PromoteCodeFragment extends Fragment implements XRecyclerView.LoadingListener {

	private View rootView;
	private XRecyclerView mRecyclerView;
	private ArrayList<UserPromoteCode> mPromoteCodeList;


	public static final String TYPE_LOAN = "1"; //贷款
	public static final String TYPE_CREDIT = "2";//信用卡
	private String mType;
	private Items mItems;
	private MultiTypeAdapter mMulitypeAdapter;

	@Override
	@Deprecated
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach (activity);

	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate (savedInstanceState);
		Bundle bundle = getArguments ();
		if (bundle != null) {
			mType = bundle.getString ("type");
		}
	}


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (rootView == null) {
			rootView = inflater
					.inflate (R.layout.promote_list, container, false);
			mRecyclerView = (XRecyclerView) rootView
					.findViewById (R.id.promoteCodeList_recyclerView);

			mRecyclerView.setLayoutManager (new LinearLayoutManager (getContext ()));
			mRecyclerView.setRefreshProgressStyle (ProgressStyle.BallSpinFadeLoader);
			mRecyclerView.setLoadingMoreProgressStyle (ProgressStyle.BallRotate);
			mRecyclerView.setLoadingListener (this);
			initMulitypeAdapter ();
			getpRromoteFromHttp ();
		} else {
			ViewGroup parent = (ViewGroup) rootView.getParent ();
			if (parent != null) {
				parent.removeView (rootView);
			}
		}
		return rootView;
	}

	private void initMulitypeAdapter() {

		mItems = new Items ();
		mMulitypeAdapter = new MultiTypeAdapter ();
		mMulitypeAdapter.register (UserPromoteCode.class, new PromoteCodeViewProvider (mItemClickListener));
		mRecyclerView.setAdapter (mMulitypeAdapter);
		mRecyclerView.setLoadingMoreEnabled (false);
		mMulitypeAdapter.setItems (mItems);
		mMulitypeAdapter.notifyDataSetChanged ();
		if (mItems.size () > 0) {
			assertAllRegistered (mMulitypeAdapter, mItems);//执行这句话时,必须保证 Items.size()>0
		}
	}

	private OnItemClickListener mItemClickListener = new OnItemClickListener () {
		@Override
		public void OnItemClick(View view, int position) {

		}

		@Override
		public void OnItemClick(View view, Object object, int position) {

			if (object instanceof UserPromoteCode) {
				UserPromoteCode code = (UserPromoteCode) object;
				Intent intent = new Intent (getActivity (),
						UserpromoteIIActivity.class);
				intent.putExtra ("title", code.getName ());
				intent.putExtra ("orgid", code.getId ());
				startActivity (intent);
			}
		}
	};

	public void getpRromoteFromHttp() {
		Log.e ("UserPromoteActivity", "getpRromoteFromHttp");
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (getActivity ());
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		params.put ("g", "Api");
		params.put ("m", "user");
		params.put ("a", "myPromocode");
		params.put ("type", mType);
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart ();
				Log.e ("PromoteCodeFragment", "OnStart");
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				if (response != null) {
					Log.e ("PromoteCode", response.toString ());

				}
				if (response != null) {
					try {
						String flag = response.getString ("flag");
						if (flag.equals ("success")) {
							JSONObject json = response.getJSONObject ("data");
							JSONArray array = json.getJSONArray ("data");
							Gson gson = new Gson ();
							Type type = new TypeToken<ArrayList<UserPromoteCode>> () {
							}.getType ();
							mPromoteCodeList = gson.fromJson (array.toString (),
									type);
							if (mPromoteCodeList != null && mPromoteCodeList.size () > 0) {
								mItems.clear ();
								mItems.addAll (mPromoteCodeList);
								if (mMulitypeAdapter != null) {
									mMulitypeAdapter.notifyDataSetChanged ();
								}
							}
						} else {
							String info = response.getString ("info");
							Toast.makeText (getActivity (), info,
									Toast.LENGTH_SHORT).show ();
						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace ();
					}
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				super.onFailure (statusCode, headers, responseString, throwable);
				Log.e ("UserPromote", "onFailure");
			}

			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				super.onFinish ();
				if (mRecyclerView != null) {
					mRecyclerView.refreshComplete ();
					mRecyclerView.loadMoreComplete ();
				}
			}
		});

	}
	/*----------------------------------------------------------------------*/

	@Override
	public void onRefresh() {
		getpRromoteFromHttp ();

	}

	@Override
	public void onLoadMore() {


	}

//	@Override
//	public void onItemClick(AdapterView<?> parent, View view, int position,
//			long id) {
//
//		if (mPromoteCodeAdapter != null) {
//			UserPromoteCode code = mPromoteCodeList.get (position - 1);
//			Intent intent = new Intent (getActivity (),
//					UserpromoteIIActivity.class);
//			intent.putExtra ("title", code.getName ());
//			intent.putExtra ("orgid", code.getId ());
//			startActivity (intent);
//		}
//	}
}
